"""
外汇数据API路由
"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from typing import Optional
from datetime import datetime
from ...models.financial import ForexData, ForexDailyData
from ...tasks.forex_tasks import collect_forex_info_task, collect_forex_daily_task
from ...utils.auth import get_current_user
import logging

router = APIRouter(
    prefix="/forex",
    tags=["外汇数据"],
    dependencies=[Depends(get_current_user)]
)

@router.get("/info")
async def get_forex_info(currency_type: Optional[str] = None):
    """获取外汇信息"""
    try:
        query = ForexData.query
        if currency_type:
            query = query.filter_by(currency_type=currency_type)
        forex = query.all()
        return [f.to_dict() for f in forex]
    except Exception as e:
        logging.error(f"获取外汇信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取外汇信息失败")

@router.post("/collect/info")
async def collect_forex_info(currency_type: Optional[str] = None):
    """触发外汇信息采集任务"""
    try:
        task = collect_forex_info_task.delay(currency_type=currency_type)
        return JSONResponse(content={"task_id": task.id})
    except Exception as e:
        logging.error(f"触发外汇信息采集任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="触发采集任务失败")

@router.get("/daily")
async def get_forex_daily(symbol: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None):
    """获取外汇日线数据"""
    try:
        query = ForexDailyData.query.filter_by(symbol=symbol)
        if start_date:
            query = query.filter(ForexDailyData.date >= start_date)
        if end_date:
            query = query.filter(ForexDailyData.date <= end_date)
        daily_data = query.order_by(ForexDailyData.date).all()
        return [data.to_dict() for data in daily_data]
    except Exception as e:
        logging.error(f"获取外汇日线数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取外汇日线数据失败")

@router.post("/collect/daily")
async def collect_forex_daily(symbol: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None):
    """触发外汇日线数据采集任务"""
    try:
        task = collect_forex_daily_task.delay(symbol=symbol, start_date=start_date, end_date=end_date)
        return JSONResponse(content={"task_id": task.id})
    except Exception as e:
        logging.error(f"触发外汇日线数据采集任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="触发采集任务失败")